/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public void treeToString(TreeNode root,StringBuilder sb){
        if(root == null) return;
        sb.append(root.val);
        if(root.left != null){
            sb.append("(");
            treeToString(root.left,sb);
            sb.append(")");
        }else{
            //root.left == null
            if(root.right == null){
                return;
            }else{
                sb.append("()");
            }
        }
        if(root.right != null){
            sb.append("(");
            treeToString(root.right,sb);
            sb.append(")");
        }else{
            return;
        }

    }

    public String tree2str(TreeNode root) {
        if(root == null) return null;
        StringBuilder sb = new StringBuilder();
        treeToString(root,sb);
        return sb.toString();
    }
}